package com.loren.demo33.event;

import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.Executor;

public class DefaultEventEngine implements EventEngine {

    /**
     * 异步执行器，如果需要的话，可以配置
     */
    private Executor executor;

    /**
     * 订阅端
     */
    private final List<BizEventListener> bizEventListeners;


    public DefaultEventEngine(List<BizEventListener> bizEventListeners) {
        this.bizEventListeners = bizEventListeners;
    }

    @Override
    public void publishEvent(BizEvent event) {
        if (CollectionUtils.isEmpty(this.bizEventListeners)) {
            return;
        }
        for (BizEventListener bizEventListener : this.bizEventListeners) {
            if (!bizEventListener.enable(event)) {
                continue;
            }
            ListenerTopic listenerTopic = bizEventListener.getClass().getAnnotation(ListenerTopic.class);
            if (listenerTopic == null) {
                continue;
            }
            if (listenerTopic.value() == null) {
                continue;
            }
            if (listenerTopic.value().equals(event.getTopic())) {
                if (this.executor != null) {
                    this.executor.execute(() -> {
                        bizEventListener.onEvent(event);
                    });
                } else {
                    bizEventListener.onEvent(event);
                }
            }
        }
    }

    public void setExecutor(Executor executor) {
        this.executor = executor;
    }
}